<?php
/**
 * Created by PhpStorm.
 * User: HS032
 * Date: 2020/8/25
 * Time: 14:12
 */

namespace ticket\modules\frontend\controllers;


use ticket\libs\Curl;
use ticket\libs\Tools;
use ticket\libs\Zhiyoubao\Zhiyoubao;
use ticket\modules\frontend\models\CouponLog;
use ticket\modules\frontend\models\ErrorMsg;
use ticket\modules\frontend\models\OrderDetails;
use ticket\modules\frontend\models\OrderInfo;
use ticket\modules\frontend\models\PayConfig;
use ticket\modules\frontend\models\TicketInfo;
use ticket\modules\frontend\models\TicketLog;
use ticket\modules\frontend\models\TicketDate;
use Yii;
use yii\base\Exception;
use yii\log\FileTarget;
use yii\web\Controller;

class PayCallbackController extends Controller
{

    /*** 门票支付回调接口
     * @return string
     */
    public function actionTicketCallback()
    {
		//$this->recordText(111111,'支付回调返回值','1');
		//$this->recordText(111111,'支付回调返回值',json_encode(Yii::$app->request->isPost));
		//$this->recordText(111111,'支付回调返回值','2');
        if (Yii::$app->request->isPost){

            $post = Yii::$app->request->post();
            $sign = isset($post['sign'])?$post['sign']:'';
//            $key = Yii::$app->params['AppId_'.$post['attach']]['key'];
            $key = $payData = $this->getPayConfig($post['attach'])['key'];
            $postSign = Tools::computeSign($post,$key);
            if ($sign == $postSign){
                if ($post['payStatus'] == '00'){
                    // 修改订单状态
                    $payNo = $post['payNo'];
                    $orderModel = OrderInfo::find()->where('order_number = :osn',[':osn' => $payNo])->one();
					//减库存
					$detailModel = OrderDetails::find()->select(['tid','reserve_time'])->where(['oid'=>$orderModel->oid])->asArray()->one();
					
					
                    if (!is_null($orderModel) and $orderModel->order_status != 3){
                        $orderModel->order_status = 3;
                        $orderModel->pay_time = $post['payTime'];
                        $orderModel->pay_number = $post['orderSn'];
                        $orderModel->save(0);
						
						 
                    }
					
					if($detailModel){
						$dateModel =TicketDate::find()->where(['tid'=>$detailModel['tid'],'date'=>substr($detailModel['reserve_time'],0,10)])->one();
						//if($dateModel->inventory>0){
							$dateModel->inventory = $dateModel->inventory>0?$dateModel->inventory - 1:0;
							$dateModel->save();
						
							$is_finish = $this->sendTicketUser($payNo,$post['orderSn']);  // 智游宝下单请求接口
							if ($is_finish){
							    OrderInfo::updateAll(['is_finish' => '1'],['oid' => $orderModel->oid]);
							}
							
						//}
						
					}
					
                   
                    $params = [
                        'relCode' => 0,
                        'msg' => '请求成功',
                    ];

                    //记录佣金
                    if($orderModel->app_id == 1 and $orderModel->share_member_id !=0 ){
                        $url = "https://shop.raysfly.com/api/share-member/add-commission-log";
                        $curl_data = [
                            'appid' =>'SHOP2020wHL09rVh09',
                            'order_id' =>$orderModel->oid,
                            'share_member_id' =>$orderModel->share_member_id,
                            'type' => 1
                        ];
                        $result = Curl::post($url,$curl_data);
                    }

                    return json_encode($params);
                    // 发送智游宝门票
                }
            }
            $this->recordText(99999,'支付回调返回值'.$postSign,json_encode($post));
        }
    }


    /*** 门票支付回调接口
     * @return string
     */
    public function actionAliTicketCallback()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $sign = isset($post['sign'])?$post['sign']:'';
            $payData = $payData = $this->getPayConfig(3);
            $key = $payData['key'];
            $postSign = Tools::computeSign($post,$key);
            if ($sign == $postSign){
                if ($post['payStatus'] == '00'){
                    // 修改订单状态
                    $payNo = $post['payNo'];
                    $orderModel = OrderInfo::find()->where('order_number = :osn',[':osn' => $payNo])->one();
                    $is_finish = $this->sendTicketUser($payNo,$post['orderSn']);  // 智游宝下单请求接口
                    if ($is_finish){
                        OrderInfo::updateAll(['is_finish' => '1'],['oid' => $orderModel->oid]);
                    }
                    if (!is_null($orderModel) and $orderModel->order_status != 3){
                        $orderModel->order_status = 3;
                        $orderModel->pay_time = $post['payTime'];
                        $orderModel->pay_number = $post['orderSn'];
                        $orderModel->save(0);
                    }

                    $params = [
                        'relCode' => 0,
                        'msg' => '请求成功',
                    ];

                    //记录佣金
                    if($orderModel->app_id == 1 and $orderModel->share_member_id !=0 ){
                        $url = "https://shop.raysfly.com/api/share-member/add-commission-log";
                        $curl_data = [
                            'appid' =>'SHOP2020wHL09rVh09',
                            'order_id' =>$orderModel->oid,
                            'share_member_id' =>$orderModel->share_member_id,
                            'type' => 1
                        ];
                        $result = Curl::post($url,$curl_data);
                    }


                    return json_encode($params);
                    // 发送智游宝门票
                }
            }
            $this->recordText(99999,'支付回调返回值'.$postSign,json_encode($post));
        }
    }


    /**** 核销通知接口   http://ticket.raysfly.com/frontend/pay-callback/ticket-verification;
     * @return string
     */
    public function actionTicketVerification()
    {
        $get = Yii::$app->request->get();
        $order_sn = isset($get['order_no'])?$get['order_no']:'';
        $status = isset($get['status'])?$get['status']:'';
        $sub_order_no = isset($get['sub_order_no'])?$get['sub_order_no']:'';
        $checkNum = isset($get['checkNum'])?$get['checkNum']:'';
        $returnNum = isset($get['returnNum'])?$get['returnNum']:'';
        $total = isset($get['total'])?$get['total']:'';
        $checkTime = isset($get['checkTime'])?$get['checkTime']:'';
        if (empty($order_sn) or empty($status)){
            throw new Exception('无订单号,通知有误');
        }
        ErrorMsg::setInfo($_SERVER['REQUEST_URI'],00000,'门票核销',json_encode($get,JSON_UNESCAPED_UNICODE));
        $transaction = Yii::$app->db->beginTransaction();
        try{
            $orderModel = OrderInfo::find()->where('pay_number = :osn',[':osn' => $order_sn])->one();
            if (is_null($orderModel)){
                throw new Exception('订单号不存在,通知有误');
            }
            $orderDetailsModel = OrderDetails::find()->where('oid = :oid',[':oid' => $orderModel->oid])->one();
            if ($orderModel->is_write_off == 1){
                $orderModel->order_status = 4;
                $orderDetailsModel->is_use = 1;
                $orderDetailsModel->verification_time = date("Y-m-d H:i:s");
            }else{
                $orderDetailsModel->is_use = 1;
                $orderDetailsModel->verification_time = date("Y-m-d H:i:s");
            }

            if ($orderDetailsModel->save(0) and $orderModel->save(0)){
                $transaction->commit();
                if ($orderModel->save(0)){
                    return 'success';
                }
            }
            throw new Exception('核销失败');
        }catch (Exception $e){
            return Tools::showRes(10405,$e->getMessage());
        }



    }


    /**** 退票通知接口   http://ticket.raysfly.com/frontend/pay-callback/refund-ticket;
     * @return string
     */
    public function actionRefundTicket()
    {
        $get = Yii::$app->request->get();
        $order_sn = isset($get['orderCode'])?$get['orderCode']:''; // 订单号
        $retreatBatchNo = isset($get['retreatBatchNo'])?$get['retreatBatchNo']:'';  //退票批次号
        $auditStatus = isset($get['auditStatus'])?$get['auditStatus']:''; // 审核状态
        $returnNum = isset($get['returnNum'])?$get['returnNum']:'';    // 退票数量
        ErrorMsg::setInfo($_SERVER['REQUEST_URI'],00000,'退票回调'.$order_sn,json_encode($get,JSON_UNESCAPED_UNICODE));
        $orderModel = OrderInfo::find()->where('pay_number = :osn',[':osn' => $order_sn])->one();
        if (is_null($orderModel)){
            die('订单号不存在,通知有误');
        }
        if ($auditStatus == 'success' ){  // 审核成功

            if ($returnNum == $orderModel->goods_num){  // 退全部票
                $orderModel->order_status = 7;
            }else{                                  // 退部分票
                $goods_num = $orderModel->goods_num - $returnNum;
                $orderModel->goods_num = $goods_num;
                $orderModel->order_status = 3;
            }
            $this->cancelCoupon($orderModel->oid,$orderModel->order_number);
        }else{
            $orderModel->order_status = 3;
        }

        if ($orderModel->save(0)){
            return 'success';
        }
    }



    public function actionSendZhiyoubao()
    {
        if  (Yii::$app->request->isPost){
            $orderSn = Yii::$app->request->post('orderSn','');
            $paySn = Yii::$app->request->post('paySn','');
            if (empty($orderSn) || empty($paySn)){
                return Tools::showRes(300,'参数有误');
            }
//            $res = $this->sendTicketUser($orderSn);
            $params = $this->getParams($orderSn,$paySn);  // 封装参数
            $zhiyoubao = new Zhiyoubao($params['aid']);
            // 门票下单
            $result = $zhiyoubao->getPlaceOrder($params);  // 下单
            return $result;
            var_dump($res);die;
        }
    }
    

    /*** 请求智游宝，门票下单，获取核销码，发送短信给用户
     * @param $orderSn
     * @return bool
     */
    protected function sendTicketUser($orderSn,$payOrderSn)
    {
        $params = $this->getParams($orderSn,$payOrderSn);  // 封装参数
		
		if(isset($params[0])){
			foreach($params as $v){
				$zhiyoubao = new Zhiyoubao($v['aid']);
				// 门票下单
				$result = $zhiyoubao->getPlaceOrder($v);  // 下单
			}
		}else{
			$zhiyoubao = new Zhiyoubao($params['aid']);
			// 门票下单
			$result = $zhiyoubao->getPlaceOrder($params);  // 下单
		}
       
        return $result;
    }


    /*** 获取支付秘钥key
     * @param $appId
     * @return array|null|\yii\db\ActiveRecord
     */
    private function getPayConfig($appId)
    {
        $payConfigModel = new PayConfig();
        $payData = $payConfigModel->getInfo($appId);
        return $payData;
    }




    protected function recordText($code,$msg,$data)
    {
        $log = new FileTarget();
        $log->logFile = Yii::$app->getRuntimePath() . '/callback/logs_' . date('Ymd') . '.log';
        $log->messages[] = [
            "[url:{$_SERVER['REQUEST_URI']}],[data:{$code},{$msg},{$data}]",
            1,
            'application',
            time(),
        ];
        $log->export();
    }

    public function getParams($orderSn,$payOrderSn)
    {
        $orderInfo =  OrderInfo::find()->where('tk_order_info.order_number = :osn',[':osn' => $orderSn])->
        joinWith(['details'])->asArray()->one();
        if($orderInfo['is_list']){
			$params = [];
			$ticket_json = json_decode($orderInfo['ticket_json'],true);
			foreach($ticket_json as $k=>$v){
				$params[] = [
				    'certificate' => $orderInfo['details']['certificate'],  // 身份证号
				    'name' => $orderInfo['details']['name'],
				    'phone' => $orderInfo['details']['phone'],
				    'order_sn' => $payOrderSn.($k+1),
				    'num' => $v['num'],
				    'price' => $v['total_price'],
				    'unit_price' => $v['rulingPrice'],
				    'ticket_sn' => $v['ticket_sn'],
				    'goods_name' => str_replace('+','',$v['goods_name']),// str_replace('+','',$orderInfo['goods_name']);
				    'describe' => '',
				    'reserveTime' => date("Y-m-d",strtotime($orderInfo['details']['reserve_time'])),
				    'aid' => $orderInfo['aid'],
				    'orderDetailsId' => $orderInfo['details']['id'],
				];
			}
			
		}else{
			$ticketInfo = TicketInfo::find()->where('tid = :id',[':id' => $orderInfo['tid']])->select(['ticket_sn','now_ticket_sn'])->asArray()->one();
			$ticketSn = $ticketInfo['ticket_sn'];
			
			// 预定时间是今天
			if (date("Y-m-d") == date("Y-m-d",strtotime($orderInfo['details']['reserve_time']))){
			    if (!empty($ticketInfo['now_ticket_sn'])){
			        $ticketSn = $ticketInfo['now_ticket_sn'];
			    }
			}
			//vip 9折票码
			if($orderInfo['details']['isvip']==1){
				$ticketSn = $ticketInfo['vip_ticket_sn'];
			}
			
			$params = [
			    'certificate' => $orderInfo['details']['certificate'],  // 身份证号
			    'name' => $orderInfo['details']['name'],
			    'phone' => $orderInfo['details']['phone'],
			    'order_sn' => $payOrderSn,
			    'num' => $orderInfo['details']['ticket_num'],
			    'price' => $orderInfo['order_amount']/100,
			    'unit_price' => $orderInfo['details']['price'],
			    'ticket_sn' => $ticketSn,
			    'goods_name' => str_replace('+','',$orderInfo['goods_name']),// str_replace('+','',$orderInfo['goods_name']);
			    'describe' => '',
			    'reserveTime' => date("Y-m-d",strtotime($orderInfo['details']['reserve_time'])),
			    'aid' => $orderInfo['aid'],
			    'orderDetailsId' => $orderInfo['details']['id'],
			];
		}
		
        return $params;
    }
    

    /*** 退票时撤销优惠券
     * @param $oid
     * @param $sn
     */
    protected function cancelCoupon($oid,$sn)
    {
        $orderInfo = CouponLog::find()->where('oid = :oid',[':oid' => $oid])->asArray()->one();
        $paramsData = [
            'channel' => 'onlineTicket',
            'memberId' => $orderInfo['member_id'],
            'couponid' => $orderInfo['coupon_id'],
            'couponname' => $orderInfo['couponname'],
            'orderId' => $sn,
            'sign' => md5('4028815173EC0DE50173FC6165E15086'.date("Ym")),

        ];

        $url = "https://xxxnk.klygf.com/ClubMemberSystem/inteface/coupon/cancel.json";
        $res = json_decode(Curl::post($url,$paramsData),true);
        if ($res['code'] == '00'){
            return true;
        }else{
            $this->recordCoupon(99999,'撤销优惠券失败-退款'.json_encode($paramsData,JSON_UNESCAPED_UNICODE),json_encode($res,JSON_UNESCAPED_UNICODE));
            return false;
        }
    }


    public function actionSendOrder()
    {
        $post = Yii::$app->request->post();
        $payNo = $post['payNo'];
        $orderSn = $post['orderSn'];
        $is_finish = $this->sendTicketUser($payNo,$orderSn);  // 智游宝下单请求接口
        if ($is_finish){
            OrderInfo::updateAll(['is_finish' => '1'],['order_number' => $payNo]);
        }
        var_dump($is_finish);die;
    }


    protected function recordCoupon($code,$msg,$data)
    {
        $log = new FileTarget();
        $log->logFile = Yii::$app->getRuntimePath() . '/coupon/use_' . date('Ymd') . '.log';
        $log->messages[] = [
            "[url:{$_SERVER['REQUEST_URI']}],[data:{$code},{$msg},{$data}]",
            1,
            'application',
            time(),
        ];
        $log->export();
    }

}